package org.jeecg.modules.drive.service;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import org.apache.commons.lang.StringUtils;
import org.jeecg.common.exception.JeecgBootException;
import org.jeecg.common.util.DateUtils;
import org.jeecg.common.util.dynamic.db.DynamicDBUtil;
import org.jeecg.modules.device.entity.DevDeviceInfo;
import org.jeecg.modules.device.mapper.DevDeviceInfoMapper;
import org.jeecg.modules.device.mapper.DevReservoirInfoMapper;
import org.jeecg.modules.drive.entity.DevDriveModel;
import org.jeecg.modules.drive.mapper.DevDriveModelMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * 数据库驱动模型公共服务类
 */

@Service
public class DriveCommonDbService {

    @Autowired
    private DevDriveModelMapper driveModelMapper;
    @Autowired
    private DevReservoirInfoMapper reservoirInfoMapper;
    @Autowired
    private DevDeviceInfoMapper devDeviceInfoMapper;
    @Autowired
    private DriveCommonInterfaceService commonInterfaceService;

    @Autowired
    private RestTemplate restTemplate;

    /***
     * 根据设备编号/序列号-读取设备数据
     * @param deviceCode 设备编码
     * @return  List<Map> deviceType（设备类型），deviceValue（设备数据值），deviceUnit(设备单位)，uniqueId（设备唯一键值）
     */
    public List<Map<String, Object>> readDeviceDataByDb(String deviceCode){
        DevDeviceInfo deviceInfo = devDeviceInfoMapper.queryByCode(deviceCode);
        if(deviceInfo.getDriveType() == 1){
            return this.readDeviceDbDataByDb(deviceInfo);
        }else if(deviceInfo.getDriveType() == 2){
            return commonInterfaceService.readDeviceDataByInterface(deviceInfo);
        }else if(deviceInfo.getDriveType() == 4){
            // 接口直连
            return commonInterfaceService.readDeviceDataByInterface(deviceInfo);
        }
        return null;
    };

    /***
     * 读取水库所有设备数据-根据监测点（水库ID）
     * @param reservoirId 监测点（水库ID）
     * @return  List<Map> deviceType（设备类型），deviceValue（设备数据值），deviceUnit(设备单位) uniqueId（设备唯一键值）
     */
    public List<Map<String, Object>> readReservoirData(String reservoirId){
        List<DevDeviceInfo> deviceInfoList = devDeviceInfoMapper.selectList(Wrappers.<DevDeviceInfo>lambdaQuery()
                .eq(DevDeviceInfo::getReservoirId, reservoirId)
                .eq(DevDeviceInfo::getDelFlag, 0));

        //分组-设备驱动模型
        List<Map<String, Object>> list=new ArrayList<>();
        for (DevDeviceInfo deviceInfo : deviceInfoList) {
            if(deviceInfo.getDriveType() == 1){
                //库表模式
                List<Map<String, Object>> deviceDatalist = this.readDeviceDbDataByDb(deviceInfo);
                // list.stream().forEach(System.out::println);
                list.addAll(deviceDatalist);
            }else if(deviceInfo.getDriveType() == 2){
                //接口模式
                List<Map<String, Object>> deviceDatalist = commonInterfaceService.readDeviceDataByInterface(deviceInfo);
                list.addAll(deviceDatalist);
            }
        }
        return list;
    };


    //库表模式
    public List<Map<String, Object>> readDeviceDbDataByDb(DevDeviceInfo deviceInfo){
        if(null == deviceInfo){
            throw new JeecgBootException("设备不存在");
        }
        /**
         * 水表	1
         * 压力表	2
         * 阀门开关	3
         * 监控抓拍	4
         * 视频监控	5
         * 水位	6
         * 雨量	7
         * 温度	8
         * 湿度	9
         */
        String deviceType = deviceInfo.getDeviceType();//设备类型
        DevDriveModel driveModel=  driveModelMapper.selectById(deviceInfo.getDriveId());
        if(null == driveModel){
            throw new JeecgBootException("设备所在设备驱动为空");
        }
        /***
         * 设备编码 需要对应 读取数据n 值
         */
        String devKey= driveModel.getReadDataType1().equals(deviceType)? driveModel.getDriveReadData1() :
                driveModel.getReadDataType2().equals(deviceType)?driveModel.getDriveReadData2():
                        driveModel.getReadDataType3().equals(deviceType)?driveModel.getDriveReadData3():
                                driveModel.getReadDataType4().equals(deviceType)?driveModel.getDriveReadData4():
                                        driveModel.getReadDataType5().equals(deviceType)?driveModel.getDriveReadData5():
                                                driveModel.getReadDataType6().equals(deviceType)?driveModel.getDriveReadData6():
                                                        driveModel.getReadDataType7().equals(deviceType)?driveModel.getDriveReadData7(): "";
        if(StringUtils.isEmpty(devKey)){
            throw new JeecgBootException("设备类型配置不能为空");
        }

        String sql="select '"+deviceType +"' as 'deviceType',"
                +devKey+" as 'deviceValue',"
                +"'"+deviceInfo.getDeviceUnit() +"' as 'deviceUnit',"
                +driveModel.getDriveUniqueId()+" as 'uniqueId'"
                +" from "+driveModel.getDriveTablename()
                +" where "+driveModel.getDriveUniqueId()+"='"+deviceInfo.getDeviceId()+"'";
        return DynamicDBUtil.findList(driveModel.getDataSourceId(), sql, null);

    }
}
